package it.polimi.registration.gui.security;

import it.polimi.registration.business.security.boundary.EventManager;
import it.polimi.registration.business.security.boundary.UserManager;
import it.polimi.registration.business.security.entity.Event;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

@Named
@RequestScoped
public class EventBean {
	@Inject
	private Logger logger;

	@EJB
	private UserManager um;

	@EJB
	private EventManager em;

	private Event event;

	@PostConstruct
	public void init() {
		try {
			String value = FacesContext.getCurrentInstance()
					.getExternalContext().getRequestParameterMap().get("event");
			int id = Integer.parseInt(value);
			event = em.getEvent(id);

		} catch(Exception ex) {
			if (event == null) {
				try {
					FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml?faces-redirect=true");
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					
				}
			}
		}
	}

	public EventBean() {

	}

	public Event getEvent() {
		return event;
	}
	public void setEvent(Event event) {
		this.event = event;
	}
	
	public boolean getIsOwner() {
		return um.getLoggedUser().equals(event.getOwner());
	}
	
	public String update() {
        try {
			em.update(event);
			return "/index.xhtml?faces-redirect=true";
		} catch(Exception e) {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			logger.log(Level.SEVERE, sw.toString());
	        logger.log(Level.SEVERE, "Update Failed");
			return null;
		}
	}
	
	public String delete() {
        try {
			em.delete(event);
			return "/index.xhtml?faces-redirect=true";
		} catch(Exception e) {
	        logger.log(Level.SEVERE, "Delete Failed");
			return null;
		}
	}
}
